using System.Collections.Generic;
using System.IO;
using System.Linq;
using System;
using System.Windows.Forms;
using System.Xml;

using MySpring;

namespace SolutionOrchestrator.Validators
{
	public class XmlDoc
	{
		readonly XmlDocument _doc;

		public XmlDocument XmlDocument
		{
			get { return _doc; }
		} 

		readonly string _fileName;
		readonly XmlNamespaceManager _nm;

		public XmlNamespaceManager Nm
		{
			get { return _nm; }
		}

		const string _nameSpaceMsbuild = "http://schemas.microsoft.com/developer/msbuild/2003";

		public string NameSpaceMsbuild
		{
			get { return _nameSpaceMsbuild; }
		} 


		public XmlDoc(string file)
		{
			_doc = new XmlDocument();
			_doc.Load(file);
			_fileName = file;
			_nm = new XmlNamespaceManager(_doc.NameTable);
			_nm.AddNamespace("x", _nameSpaceMsbuild);
		}


		public IEnumerable<XmlNode> Select(string xpath)
		{
			return _doc.SelectNodes(xpath, _nm).Cast<XmlNode>();
		}

		public XmlNode SelectSingle(string xpath)
		{
			return _doc.SelectSingleNode(xpath, _nm);
		}

		public string FileName
		{
			get { return _fileName; }
		}


		public void Save()
		{
			try
			{
				if ((File.GetAttributes(_fileName) & FileAttributes.ReadOnly) > 0)
				{
					var sc = SpringContainer.Root.Get<IMySettingsProvider>().Get.SourceControl;
					if (sc != null)
					{
						sc.Checkout(_fileName);
					}
					else
					{
						throw new Exception("Unable to get source control manager");
					}
				}
				if ((File.GetAttributes(_fileName) & FileAttributes.ReadOnly) > 0)
				{
					throw new Exception("Source control does not cleared ReadOnly attribute");
				}
				try
				{
					_doc.Save(_fileName);
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
			catch (Exception ex)
			{
				var ctx = SpringContainer.Root.Get<DataCtx>();
				ctx.ShowSourceControlSettings = true;
				ctx.SourceControlErrorFile = _fileName;
				ctx.SourceControlError = ex.Message;
			}
		}
	}
}